import os.path
AdMap = {
    "ad-tip": "",
    "ad-note": ""
}


def O2R(md_source: str,convAd = True,convPath = True) -> str:
    mdLines: list[str] = md_source.splitlines()
    content = ""
    stack: list[str] = []
    for line in mdLines:
        lineStrip = line.strip()
        # 代码段结束
        if lineStrip == "```":
            buf: list[str] = []
            while True:
                pop = stack.pop()
                popStrip = pop.strip()
                if popStrip.startswith("```") and popStrip.strip() != "```":
                    codeLang: str = popStrip[3:]
                    # 是特殊代码块
                    if codeLang in AdMap and convAd:
                        title = AdMap[codeLang]
                        if title:
                            buf.append("")
                            buf.append(title)
                        buf = ["> " + i for i in buf]
                    else:
                        buf = [line] + buf + [pop]
                    buf.reverse()
                    stack.append("\n".join(buf))
                    break
                buf.append(pop)
            continue
        # Image
        if convPath and lineStrip.startswith("![[") and lineStrip.endswith("]]"):
            path = lineStrip[3:-2]
            pathSplit = path.split("|")
            path = pathSplit[0]
            path = "images/" + os.path.basename(path)
            path = path.replace(" ","%20")
            stack.append(f"![img]({path})")
            continue
        stack.append(line)
    return "\n".join(stack)


def ReadAllText(path: str) -> str:
    with open(path, 'r', encoding='utf-8') as f:
        return f.read()

if __name__ == "__main__":
    inp = ReadAllText("./从 Unity 到 Godot.md")
    res = O2R(inp)
    with open("./README.md", 'w', encoding='utf-8') as f:
        f.write(res)
